import { defineStore } from "pinia";
import { ref } from "vue";
import { login, logout } from "@/services/api";
import { useCookies } from "vue3-cookies";

export const useAuthStore = defineStore("auth", () => {
  const { cookies } = useCookies();
  const isAuthenticated = ref(cookies.get("logined") === "true");

  const loginUser = async (username: string, password: string) => {
    try {
      const response = await login(username, password);
      if (response.data.code !== 0) {
        throw new Error(response.data.msg);
      }
      isAuthenticated.value = true;
    } catch (error) {
      throw error;
    }
  };

  const logoutUser = async () => {
    try {
      await logout();
    } catch (error) {
      console.error("Logout failed:", error);
    }
    isAuthenticated.value = false;
  };

  return {
    isAuthenticated,
    loginUser,
    logoutUser,
  };
});
